<script setup>
import topNav from "../../components/topNav.vue";
import {
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  computed,
  nextTick,
} from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import {
  appProductQuery,
  salePriceCreate,
  saleShopPriceCreate,
} from "@/services/goods";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");

onLoad((option) => {
  console.log("asdasdds", option);
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";
  if (uni.getStorageSync("selectShopType")) {
    showSelect.value = uni.getStorageSync("selectShopType");
  }
});
const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getAppProductQuery(1);
};

const searchFun = (val) => {
  console.log("取2消");
  form.value.keyword = val;
  loading.value = "";
  console.log(form.value.name);
  getAppProductQuery(1);
};

onReachBottom(() => {
  console.log("触底了");
  getAppProductQuery();
});
onMounted(() => {
  getAppProductQuery();
});

//获取商品
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 20,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  keyword: "",
});

const productData = ref([]);

const loading = ref("");
const getAppProductQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await appProductQuery(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//改价模块
const showSelect = ref("");
const itemObj = ref({});
const selectitem = ref(0);
const num = ref(0);
const show = ref(false);
const showKeyboard = ref(true);
const priceValue = ref("30.10");
const keyboard = ref(null);
const keyboardHeight = ref(0);
const isSr = ref(false);
const themeVars = ref({
  numberKeyboardBackground: "#F7F8FA ",
  numberKeyboardKeyBackground: "#FFFFFF",
  numberKeyboardButtonBackground: "#FF5722",
});

const onClickItem = (item, index) => {
  if (showSelect.value == "shop") {
    if (!item.storePricing) {
      uni.showToast({
        title: "该商品不支持门店改价",
        icon: "none",
      });

      return;
    }
  }
  itemObj.value = item;
  selectitem.value = index;
  priceValue.value = String(item.salePrice);
  selectNumIndex.value = -1;
  keyWord.value.open();
  // show.value = true;
  // showKeyboard.value = true;
  // nextTick(() => {
  //   setTimeout(() => {
  //     keyboardHeight.value = keyboard.value.$el.offsetHeight;
  //     console.log(keyboard.value.$el.offsetHeight, keyboard.value);
  //   }, 100);
  // });
};
const onInput = (item) => {
  setTimeout(() => {
    priceValue.value = handlePriceInput(priceValue.value);
  }, 100);

  console.log(item);
};
const handlePriceInput = (event) => {
  let value = event;

  // 过滤掉非数字和小数点的字符
  value = value.replace(/[^0-9.]/g, "");

  // 确保只有一个小数点
  const parts = value.split(".");
  if (parts.length > 2) {
    value = parts[0] + "." + parts.slice(1).join("");
  }

  // 如果以小数点开头，添加 '0'
  if (value.startsWith(".")) {
    value = "0" + value;
  }

  // 如果小数点后超过两位，截断
  const decimalParts = value.split(".");
  if (decimalParts.length === 2 && decimalParts[1].length > 2) {
    value = decimalParts[0] + "." + decimalParts[1].slice(0, 2);
  }
  console.log("value", value);
  // form.value.price = value;
  return value;
};
//提交改价

const onBlue = async () => {
  try {
    let res = await salePriceCreate({
      productId: itemObj.value.id,
      revisePrice: priceValue.value,
      description: "手机端操作",
    });
    if (res.code == 200) {
      showToast("修改成功");
      num.value = num.value + 1;
      productData.value[selectitem.value].newsalePrice = priceValue.value;
      // productData.value[selectitem.value].salePrice=priceValue.value

      // getAppProductQuery(1);
      show.value = false;
    } else {
      showToast(res.msg);
    }
  } catch (e) {
    showToast(e.msg);
  }
};
const goRecord = () => {
  uni.navigateTo({
    url: "/pages/goods/goods_price_record/index",
  });
};

const keyWord = ref(null);
const selectNumIndex = ref(-1);
const del = (e) => {
  if (e == 0) {
    selectNumIndex.value = selectNumIndex.value - 1;
  } else if (e == 1) {
    selectNumIndex.value = selectNumIndex.value + 1;
  }
};
const keyWordItem = (index) => {
  selectNumIndex.value = index;
};
//金额键盘
const inp = (e) => {};

const hide = () => {
  if (num.value > 0) {
    // numblur();
  } else {
    jsnum.value = 0;
  }
  isinputto.value = false;
  isshowput.value = true;
};
const confirm = async () => {
  let res = null;

  // saleShopPriceCreate;
  // getcomputeBrokerage(Number(num.value));
  try {
    let res = null;
    if (showSelect.value == "shop") {
      res = await saleShopPriceCreate({
        productId: itemObj.value.id,
        revisePrice: priceValue.value,
        description: "手机端操作",
      });
      if (res.code == 200) {
        uni.showToast({
          title: "修改成功",
          icon: "none",
        });
        num.value = num.value + 1;
        productData.value[selectitem.value].newsalePrice = priceValue.value;
        // productData.value[selectitem.value].salePrice=priceValue.value
        nextTick(() => {
          keyWord.value.close();
          // isshowput.value = true;
        });

        // getAppProductQuery(1);
        show.value = false;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    } else {
      res = await salePriceCreate({
        productId: itemObj.value.id,
        revisePrice: priceValue.value,
        description: "手机端操作",
      });
      if (res.code == 200) {
        uni.showToast({
          title: "修改成功",
          icon: "none",
        });
        num.value = num.value + 1;
        productData.value[selectitem.value].newsalePrice = priceValue.value;
        // productData.value[selectitem.value].salePrice=priceValue.value
        nextTick(() => {
          keyWord.value.close();
          // isshowput.value = true;
        });

        // getAppProductQuery(1);
        show.value = false;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};
const numblur = () => {
  // getcomputeBrokerage(Number(num.value));
};
const closePay = () => {
  keyWord.value.close();
};

const ishowcamera = ref(false);
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=price" });
  // #endif
  // 允许从相机和相册扫码
  // #ifdef APP-PLUS

  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  code.value = res.result;
                  getAppProductQuery(1);

                  // uni.navigateTo({
                  //   url: "/pages/goods/goods_price_search/index?code=" + res.result,
                  // });
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      code.value = res.result;
      getAppProductQuery(1);

      // uni.navigateTo({
      //   url: "/pages/goods/goods_price_search/index?code=" + res.result,
      // });
    },
  });
  // #endif
};
</script>

<template>
  <topNav
    title="商品搜索"
    @save="saveFun"
    rType="cancel"
    @search="searchFun"
    @scan="scanFun"
    :IsSearch="true"
    :code="code"
  ></topNav>

  <jia-PayKeyboard
    v-permission="['manager:salePrice:create', 'shop:salePrice:create']"
    :confirmStyle="{ backgroundColor: '#1679FB' }"
    class="keyWord-index"
    :overlayClose="true"
    ref="keyWord"
    v-model="priceValue"
    :sclectItem="selectNumIndex"
    @del="del"
    @input="inp"
    @confirm="confirm"
    @hide="hide"
  >
    <view class="PayKeyboard-k">
      <view class="icon-top">
        <up-icon
          @click="closePay"
          name="close"
          color="#86909C"
          size="20"
        ></up-icon
      ></view>
      <view class="PayKeyboard-k-title">{{ itemObj.name }}</view>
      <view class="PayKeyboard-k-des">{{ itemObj.barCode }}</view>
      <view class="link-to"></view>
      <view class="PayKeyboard-k-num">
        <view class="PayKeyboard-k-num-title">新售价</view>
        <view class="PayKeyboard-k-num-input">
          <up-form labelPosition="left" ref="form1" labelWidth="0">
            <up-form-item
              label=" "
              borderBottom
              ref="item1"
              @click="keyWordItem(-1)"
            >
              <view class="PayKeyboard-k-num-input-text">
                <view
                  class="num-view"
                  v-for="(item, index) in priceValue"
                  :key="index"
                  @click.stop="keyWordItem(index)"
                  ><view class="input_lin" v-if="selectNumIndex == index"></view
                  >{{ item }}</view
                >
                <view class="input_lin" v-if="selectNumIndex == -1"></view>
              </view>
              <template #right>
                <text>元</text>
              </template>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </view>
  </jia-PayKeyboard>
  <view class="goods_form">
    <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickItem(item, index)"
    >
      <view class="scroll-item-left">
        <image :src="item.image" mode="scaleToFill" />
      </view>
      <view class="scroll-item-right">
        <view class="goods-item-title">
          {{ item.name }}
          <text
            v-if="!item.available"
            style="margin-left: 10rpx; white-space: nowrap; color: #ff5722"
            >禁用</text
          ></view
        >
        <view class="goods-item-spec">
          条形码: {{ item.barCode ? item.barCode : "--" }}
        </view>
        <view class="goods-item-price">
          <text
            >¥{{ item.salePrice ? item.salePrice : 0.0 }}
            {{ item.unit ? "/" + item.unit : "" }}</text
          >
          <text v-if="item.newsalePrice" class="color-blue"
            >调后价¥{{ item.newsalePrice }}</text
          >
        </view>
      </view>
    </view>
    <!-- <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickItem(item, index)"
    >
      
      <view class="scroll-item-right">
        <view class="goods-item-title"
          ><text>{{ item.name }}</text>
          <text v-if="item.newsalePrice">原价:{{ item.salePrice }}</text>
        </view>
        <view class="goods-item-price">
          <text> 条形码: {{ item.barCode ? item.barCode : "--" }}</text>
          <text class="color-blue"
            >¥{{
              item.newsalePrice
                ? item.newsalePrice
                : item.salePrice
                ? item.salePrice
                : "--"
            }}{{ item.unit ? "/" + item.unit : "" }}</text
          >
        </view>
      </view>
    </view> -->
  </view>
  <!-- v-if="productData.length <= 0 && !loading" -->
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无商品 </view>
    </view>
  </view>

  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>
  <view style="width: 100%; height: 200rpx"></view>
  <view class="goods_bt">
    <view class="goods_bt_to">
      <text>本次调价{{ num }}款</text>
      <van-button class="val-button" type="primary" @click="goRecord"
        >调价记录</van-button
      >
    </view>
  </view>

  <!-- <view class="mask-k" v-if="show" @click="show = false"></view> -->
  <!--  -->
  <!-- <view
    class="select_price"
    :style="'bottom:' + keyboardHeight + 'px;'"
    :class="!show ? 'select_price_noshow' : ''"
  >
    <view class="select_price_tag" @click="show = false">
      <van-icon name="cross" size="28rpx" color="#86909C" />
    </view>
    <view class="select_price_top">
      <view class="select_price_title">{{ itemObj.name }}</view>
      <view class="select_price_des">{{ itemObj.barCode }}</view>
    </view>
    <view class="select_price_in">
      <view class="select_price_title">新售价 </view>
      <view>
        <van-field
          v-model="priceValue"
          readonly
          clickable
          @touchstart.stop="show = true"
          class="select_price_input"
        >
          <template #button>
            <text>元</text>
          </template>
        </van-field>
      </view>
    </view>
  </view>
  <van-config-provider :theme-vars="themeVars">
    <van-number-keyboard
      :transition="true"
      :hide-on-click-outside="false"
      ref="keyboard"
      class="priceKey"
      v-model="priceValue"
      :show="show"
      theme="custom"
      extra-key="."
      close-button-text="完成"
      @blur="onBlue"
      @input="onInput"
      @delete="onDelete"
      z-index="50"
    />
  </van-config-provider> -->

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
